package com.zxl.service.impl;

import com.alibaba.fastjson2.JSON;
import com.zxl.enums.MmMessageEnums;
import com.zxl.feign.MmMessageFeign;
import com.zxl.mapper.MetaTableMapper;
import com.zxl.model.MetaTable;
import com.zxl.model.dto.MmMessageDto;
import com.zxl.service.MetaTableService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
@Service
public class MetaTableServiceImpl implements MetaTableService {
    @Value("${spring.application.name}")
    private String appName;
    @Resource
    private MmMessageFeign messageFeign;
    @Resource
    private MetaTableMapper metaTableMapper;
    private static final String MQ_NEO4J_ROUTING_KEY = "neo4j.routing.key";

    @Override
    public void update(MetaTable metaTable) {
        //更新血缘信息
        // datarelationFeignClient.updateTableRelation(metaTable);
        //更新业务数据库的meta_table表信息
        //metaTableMapper.updateByPrimaryKeySelective(metaTable);
    }

    public void deleteById(Integer id) {
        MetaTable metaTable = metaTableMapper.selectByPrimaryKey(id);
        //发送“待发送”的订单消息给我msg5001微服务，对应设计图步骤1
        sendNeo4jPrepareMsg(metaTable);
        //执行本地事务提交，对应设计图步骤3
        deleteTableById(id);
        //int age = 10/0;
        //通知消息可以发送了，对应设计图步骤4
        sendNeo4jConfirmMsg(metaTable);
    }

    private void sendNeo4jConfirmMsg(MetaTable metaTable) {
        MmMessageDto msgDTO = new MmMessageDto();
        String messageId = MmMessageEnums.NEO4J.getCode() + "-" + metaTable.getId();
        msgDTO.setMsgId(messageId);
        this.messageFeign.confirmMsg(msgDTO);
    }

    private void sendNeo4jPrepareMsg(MetaTable metaTable) {
        MmMessageDto msgDTO = new MmMessageDto();
        String messageId = MmMessageEnums.NEO4J.getCode() + "-" + metaTable.getId();
        msgDTO.setMsgId(messageId);
        msgDTO.setAppName(appName);
        msgDTO.setRoutingKey(MQ_NEO4J_ROUTING_KEY);
        msgDTO.setJsonMsg(JSON.toJSONString(metaTable));
        this.messageFeign.prepareMsg(msgDTO);
    }

    @Transactional
    public void deleteTableById(Integer tableId) {
        // TODO 远程数据删除表
        metaTableMapper.deleteByPrimaryKey(tableId);
    }

}
